#include <iostream>
#include <string>
#include <signal.h>

#include "oj_control.hpp"
#include "../comm/httplib.h"

using namespace std;
using namespace httplib;
using namespace ns_control;

static Control *ctrl_ptr = nullptr;

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main()
{
    signal(SIGQUIT, Recovery);

    // 用户请求的服务路由功能
    Server srv;
    Control ctrl;
    ctrl_ptr = &ctrl;

    // 获取所有的题目列表
    srv.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
    {
        string html;
        ctrl.AllQuestions(&html);
        resp.set_content(html, "text/html; charset=utf-8");
    });

    // 用户要根据题目的编号，获取题目的内容
    // /question/100 -> 正则匹配
    // R"(), 原始字符串raw string, 保持字符串内容的原貌, 不用做相关转义
    srv.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
    {
        string number = req.matches[1]; // 固定写法
        string html;
        ctrl.Question(number, &html);
        resp.set_content(html, "text/html; charset=utf-8");
    });

    // 用户提交代码，使用我们的判题功能(1. 每道题的测试用例 2. compile_and_run)
    srv.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
    {
        string number = req.matches[1];
        string result_json;
        ctrl.Judge(number, req.body, &result_json);
        resp.set_content(result_json, "application/json; charset=utf-8");
    });

    srv.set_base_dir("./wwwroot");
    srv.listen("0.0.0.0", 8080);
    
    return 0;
}
